﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WeiboSDK;

namespace Cnblogs
{
    public partial class SendWeiboPage : PhoneApplicationPage
    {
        private bool _isLoaded = false;
        public SendWeiboPage()
        {
            InitializeComponent();
            InitAppbar();
            Loaded += new RoutedEventHandler(SendWeiboPage_Loaded);
        }

        void SendWeiboPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!_isLoaded)
            {
                _isLoaded = true;
                this.ptb_status.Text = App.Status.Length > 140 ? App.Status.Substring(0, 135) + "..." : App.Status;
                if (!string.IsNullOrEmpty(App.ShareImagePath))
                {
                    LowProfileImageLoader.SetUriSource(imgWeibo, new Uri(App.ShareImagePath, UriKind.Absolute));
                }
            }
        }

        #region Appbar

        private ApplicationBarIconButton _sendButton;
        private void InitAppbar()
        {
            if (base.ApplicationBar == null)
            {
                base.ApplicationBar = new ApplicationBar();
            }
            _sendButton = new ApplicationBarIconButton(new Uri("/Images/appbar_send.png", UriKind.Relative));
            _sendButton.Text = "发送";
            _sendButton.Click += (e1, e2) =>
            {
                Send();
            };

            base.ApplicationBar.Buttons.Add(_sendButton);


        }

        #endregion

        private void Send()
        {
            this.Focus();

            grid.Visibility = System.Windows.Visibility.Visible;
            tbk_busy.Text = Constants.L_SendingWeibo;
            if (sb_busy != null)
            {
                sb_busy.Begin();
            }
            WeiboAPI.UploadWeibo(this.ptb_status.Text, GlobalFunc.getShareImagePath(), App.Token, (p) =>
                {

                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        grid.Visibility = System.Windows.Visibility.Collapsed;
                        if (p == Status.Ok)
                        {
                            if (NavigationService.CanGoBack)
                            {
                                NavigationService.GoBack();
                            }
                            App.Status = "";
                            App.ShareImagePath = "";
                        }
                    });

                });
        }
    }
}